package com.devops.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devops.admin.mapper.DOSKubernetesResourceMapper;
import com.devops.admin.model.*;
import com.devops.admin.po.DOSKubernetesResourcePo;
import com.devops.admin.po.DOSProjectPo;
import com.devops.admin.service.*;
import com.devops.admin.util.Assert;
import com.devops.admin.util.CertManagerClientUtil;
import com.devops.admin.util.K8sClientUtil;
import com.devops.admin.util.YamlUtils;
import com.devops.admin.vo.DOSKubernetesResourceVo;
import com.devops.admin.vo.DOSNamespaceChart;
import com.devops.admin.vo.DOSPageVo;
import com.devops.admin.vo.DOSProjectVo;
import com.devops.common.utils.Message;
import com.devops.constant.DevOpsConstant;
import com.devops.shiro.vm.BaseUserVM;
import io.fabric8.certmanager.api.model.v1.*;
import io.fabric8.certmanager.client.CertManagerClient;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName DOSKubernetesResourceServiceImpl
 * @Description TODO
 * @Author heyabo
 * @Date 2022/8/11 14:47
 * @Version 1.0
 **/
@Slf4j
@Service
public class DOSKubernetesResourceServiceImpl extends ServiceImpl<DOSKubernetesResourceMapper, DOSKubernetesResource> implements DOSKubernetesResourceService {

    @Autowired
    private DOSClusterInfoService dosClusterInfoService;
    @Autowired
    private DOSClusterNamespaceService dosClusterNamespaceService;
    @Autowired
    private DOSKubernetesYamlRelationService dosKubernetesYamlRelationService;
    @Autowired
    private DOSProjectOutService dosProjectOutService;
    @Autowired
    @Lazy
    private DOSK8sResourceEventService dosk8sResourceEventService;
    @Value("${project.similarity.limit}")
    private Double similarityLimit;

    @Override
    public Message applyProject(DOSKubernetesResourceVo kubernetesResource) {

        Assert.isTrue(kubernetesResource.getProjectId() != null && kubernetesResource.getProjectId() > 0,"项目id不能为空");
        Assert.isTrue(kubernetesResource.getClusterId() != null && kubernetesResource.getClusterId() > 0,"集群id不能为空");
        Assert.isTrue(kubernetesResource.getEnvTypeId() != null && kubernetesResource.getEnvTypeId() > 0,"环境类型id不能为空");
        Assert.isTrue(kubernetesResource.getNamespaceId() != null && kubernetesResource.getNamespaceId() > 0,"命名空间id不能为空");
        Assert.isTrue(StrUtil.isNotBlank(kubernetesResource.getYamlValues()),"yaml内容不能为空");

        // 解析yaml，生成kubernetesResource集合
        List<DOSKubernetesResource> kubernetesResources = getDeployment(kubernetesResource,1);
        Assert.isTrue(CollectionUtil.isNotEmpty(kubernetesResources),"yaml文件解析失败");

        // 获取集群的ConfigContent
        List<DOSClusterInfo> clusterInfos = dosClusterInfoService
                .list(Wrappers.<DOSClusterInfo>lambdaQuery()
                        .eq(DOSClusterInfo::getClusterId, kubernetesResource.getClusterId()));
        Assert.isTrue(CollectionUtil.isNotEmpty(clusterInfos), "请检查集群id是否合法");
        Assert.isTrue(clusterInfos.size() == 1,"查询集群的ConfigContent数据出错");

        // 获取k8s服务连接client
        KubernetesClient client = K8sClientUtil.getKubernetesClient(clusterInfos.get(0).getConfigPath(), clusterInfos.get(0).getConfigContent());

        List<DOSKubernetesResource> kubernetes = new ArrayList<>();
        List<DOSKubernetesYamlRelation> kubernetesYamlRelations = new ArrayList<>();
        try{
            for (DOSKubernetesResource resource : kubernetesResources) {
                log.info("部署yaml：{}", resource.getYamlValue());
                // 根据yaml文件部署项目
                InputStream inputStream = new ByteArrayInputStream(resource.getYamlValue().getBytes(StandardCharsets.UTF_8));
                List<HasMetadata> results = client.load(inputStream).inNamespace(resource.getNamespace()).serverSideApply();
                // 部署失败直接返回false
                if (CollectionUtil.isEmpty(results)) {
                    return Message.error("部署"+resource.getKind()+",操作失败，请检查yaml文件");
                }
                kubernetes.add(resource);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Message.error("部署失败："+ e.getMessage());
        }finally {
            if (CollectionUtil.isNotEmpty(kubernetes)){
                // 如果存在部署成功地，则在最后进行批量插入，节省io
                this.saveBatch(kubernetes);
                kubernetes.forEach(kubernete -> {
                    DOSKubernetesYamlRelation kubernetesYamlRelation = DOSKubernetesYamlRelation.builder()
                            .kubernetesResourceId(kubernete.getId())
                            .yamlValue(kubernete.getYamlValue())
                            .yamlRevision(1)
                            .build();
                    kubernetesYamlRelations.add(kubernetesYamlRelation);
                });
                if (CollectionUtil.isNotEmpty(kubernetesYamlRelations)){
                    // 批量添加
                    dosKubernetesYamlRelationService.saveBatch(kubernetesYamlRelations);
                }
            }
            client.close();
        }
        JSON json = new JSONObject();
        kubernetes.forEach(k -> {
            if ("Deployment".equals(k.getKind())){
               json.putByPath("releaseId",k.getId());
            }
        });
        return Message.ok(json);
    }

    @Override
    public Message upgradeProject(DOSKubernetesResourceVo kubernetesResource) {
        Assert.isTrue(kubernetesResource.getKubernetesResourceId() != null && kubernetesResource.getKubernetesResourceId() > 0,"k8s资源id不能为空");
        Assert.isTrue(StrUtil.isNotBlank(kubernetesResource.getYamlValues()),"yaml文件内容不能为空");

        DOSKubernetesResource dosKubernetesResource = this.getById(kubernetesResource.getKubernetesResourceId());
        Assert.isTrue(dosKubernetesResource != null,"请检查k8s资源id是否合法");
        kubernetesResource.setProjectId(dosKubernetesResource.getProjectId());
        kubernetesResource.setClusterId(dosKubernetesResource.getClusterId());
        kubernetesResource.setEnvTypeId(dosKubernetesResource.getEnvTypeId());
        kubernetesResource.setNamespaceId(dosKubernetesResource.getNamespaceId());

        // 解析yaml文件
        List<DOSKubernetesResource> resources = getDeployment(kubernetesResource,2);
        Assert.isTrue(CollectionUtil.isNotEmpty(resources),"yaml文件解析失败");
        Assert.isTrue(resources.size() == 1,
                "请保证升级的yaml只有"+dosKubernetesResource.getKind()+"，且名字为："+dosKubernetesResource.getName()+"的yaml进行升级");

        // 校验升级前后关键属性是否一直
        DOSKubernetesResource resource = resources.get(0);
        Assert.isTrue(resource.getKind().equals(dosKubernetesResource.getKind()),"yaml文件的kind属性升级前后不一致");
        Assert.isTrue(resource.getName().equals(dosKubernetesResource.getName()),"yaml文件的name属性升级前后不一致");
        Assert.isTrue(resource.getNamespace().equals(dosKubernetesResource.getNamespace()),"yaml文件的namespace属性升级前后不一致");

        // 获取集群的ConfigContent
        List<DOSClusterInfo> clusterInfos = dosClusterInfoService
                .list(Wrappers.<DOSClusterInfo>lambdaQuery()
                        .eq(DOSClusterInfo::getClusterId, dosKubernetesResource.getClusterId()));
        Assert.isTrue(CollectionUtil.isNotEmpty(clusterInfos), "请检查集群id是否合法");
        Assert.isTrue(clusterInfos.size() == 1,"查询集群的ConfigContent数据出错");

        // 获取k8s服务连接client
        try (KubernetesClient client = K8sClientUtil.getKubernetesClient(clusterInfos.get(0).getConfigPath(), clusterInfos.get(0).getConfigContent())) {
            // 根据yaml文件部署项目
            InputStream inputStream = new ByteArrayInputStream(resource.getYamlValue().getBytes(StandardCharsets.UTF_8));
            List<HasMetadata> results = client.load(inputStream).inNamespace(resource.getNamespace()).createOrReplace();
            // 升级失败直接返回false
            if (CollectionUtil.isEmpty(results)) {
                return Message.error("升级" + resource.getKind() + "操作失败，请检查yaml文件");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Message.error("升级失败：" + e.getMessage());
        }

        // 更新yaml
        resource.setId(dosKubernetesResource.getId());
        this.updateById(resource);
        DOSKubernetesYamlRelation kubernetesYamlRelation = DOSKubernetesYamlRelation.builder()
                .kubernetesResourceId(resource.getId())
                .yamlValue(resource.getYamlValue())
                .build();
        synchronized (this) {
            dosKubernetesYamlRelationService.saveHistory(kubernetesYamlRelation);
        }

        return Message.ok("升级成功");
    }

    @Override
    public Message removeProject(Integer kubernetesResourceId) {
        DOSKubernetesResource resource = this.getById(kubernetesResourceId);
        Assert.isTrue(resource != null,"请检查k8s资源id是否正确");

        // 获取集群的ConfigContent
        List<DOSClusterInfo> clusterInfos = dosClusterInfoService
                .list(Wrappers.<DOSClusterInfo>lambdaQuery()
                        .eq(DOSClusterInfo::getClusterId, resource.getClusterId()));
        Assert.isTrue(CollectionUtil.isNotEmpty(clusterInfos), "请检查集群id是否合法");
        Assert.isTrue(CollectionUtil.isNotEmpty(clusterInfos) && clusterInfos.size() == 1,"查询集群的ConfigContent数据出错");

        // 获取k8s服务连接client

        try (KubernetesClient client = K8sClientUtil.getKubernetesClient(clusterInfos.get(0).getConfigPath(), clusterInfos.get(0).getConfigContent())) {
            // 根据yaml文件部署项目
            InputStream inputStream = new ByteArrayInputStream(resource.getYamlValue().getBytes(StandardCharsets.UTF_8));
            // 卸载deployment的核心代码
            boolean isDelete = !client.load(inputStream)
                    .inNamespace(resource.getNamespace())
                    .delete()
                    .isEmpty();
            if (!isDelete) {
                return Message.error("卸载失败,请检查yaml文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error("卸载失败：" + e.getMessage());
        }

        // 删除k8s资源
        this.removeById(kubernetesResourceId);

        return Message.ok("卸载成功");
    }

    @Override
    public List<DOSKubernetesResourcePo> getList(DOSKubernetesResourceVo kubernetesResource) {
        Assert.isTrue(kubernetesResource.getProjectId() != null && kubernetesResource.getProjectId() > 0,"项目id不能为空");
        return baseMapper.getList(kubernetesResource);
    }

    @Override
    public TableResult<DOSKubernetesResourcePo> getPageList(DOSKubernetesResourceVo kubernetesResource, DOSPageVo pageVo) {
        BaseUserVM user = (BaseUserVM) SecurityUtils.getSubject().getPrincipal();
        Page<DOSKubernetesResourcePo> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        TableResult<DOSKubernetesResourcePo> tableResult = new TableResult<>();
        if (!user.getAdminRole()){
            // 如果是管理员级别以下的用户，则需要根据自己所在的项目组，或者项目查看相应的release
            DOSProjectVo projectVo = DOSProjectVo.builder()
                    .userId(user.getId()).build();
            List<DOSProjectPo> projects = dosProjectOutService.getProjectsByUserId(projectVo);
            // 如果项目列表为空则表明当前用户不可查看release列表
            if (CollectionUtil.isEmpty(projects) || projects.size() < 1){
                return tableResult;
            }
            // 获取项目id列表并去重
            List<Integer> projectIds = projects.stream().map(DOSProjectPo::getId).distinct().collect(Collectors.toList());
            kubernetesResource.setProjectIds(projectIds);
        }
        List<DOSKubernetesResourcePo> kubernetesResourcePos = baseMapper.getPageaList(kubernetesResource,page);
        // 如果k8s的资源为空则没有必要再往下查询
        if (CollectionUtil.isEmpty(kubernetesResourcePos)){
            return null;
        }
        List<Integer> resourceIds = kubernetesResourcePos.stream().map(DOSKubernetesResourcePo::getId).collect(Collectors.toList());
        // 查询yaml文件的历史版本
        LambdaQueryWrapper<DOSKubernetesYamlRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DOSKubernetesYamlRelation::getKubernetesResourceId,resourceIds)
                .orderByDesc(DOSKubernetesYamlRelation::getYamlRevision);
        List<DOSKubernetesYamlRelation> yamlRelations = dosKubernetesYamlRelationService.list(queryWrapper);
        // 为列表中的数据赋值yaml的版本号
        kubernetesResourcePos.forEach(kubernetes -> {
            for (DOSKubernetesYamlRelation yamlRelation : yamlRelations) {
                if (kubernetes.getId().intValue() == yamlRelation.getKubernetesResourceId()
                        && (kubernetes.getYamlRevision() == null || kubernetes.getYamlRevision() < 1)){
                    kubernetes.setYamlRevision(yamlRelation.getYamlRevision());
                    break;
                }
            }
        });
        Pagination p = Pagination.builder().pageNum(page.getCurrent()).pageSize(page.getSize()).total(page.getTotal()).build();
        tableResult.setPagination(p);
        tableResult.setList(kubernetesResourcePos);
        return tableResult;
    }

    @Override
    public List<DOSKubernetesYamlRelation> getHistorys(Integer kubernetesResourceId) {
        LambdaQueryWrapper<DOSKubernetesYamlRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DOSKubernetesYamlRelation::getKubernetesResourceId,kubernetesResourceId);
        queryWrapper.orderByDesc(DOSKubernetesYamlRelation::getYamlRevision);

        return dosKubernetesYamlRelationService.list(queryWrapper);
    }

    @Override
    public DOSNamespaceChart getInfoById(Integer releaseId) {
        return baseMapper.getInfoById(releaseId);
    }


    /**
     * @Author heyabo
     * @Description 解析yaml文件
     * @Date 16:10 2022/8/10
     * @Param [yaml]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    private List<DOSKubernetesResource> getDeployment(DOSKubernetesResourceVo kubernetesResource,int type) {

        // 根据id获取命名空间id
        DOSClusterNamespace clusterNamespace = dosClusterNamespaceService.getById(kubernetesResource.getNamespaceId());

        List<DOSKubernetesResource> kubernetesResources = new ArrayList<>();
        String yaml = kubernetesResource.getYamlValues();
        String[] yamls = yaml.split("---");
        // 将yaml文件拆分成多份
        for (String value : yamls) {
            if (StrUtil.isBlank(value)) {
                continue;
            }
            // 根据key获取kind
            String kind = (String) YamlUtils.getValues("kind",value);
            // 根据key获取apiVersion
            String apiVersion = (String) YamlUtils.getValues("apiVersion",value);
            // 根据key获取name
            String name = (String) YamlUtils.getValues("metadata.name",value);
            // 只有第一次部署的时候才允许修改yaml文件
            if (type == 1) {
                Map<String, Object> map = getLabelsValueToAddYaml(kubernetesResource.getProjectId(), value, name);
                // 添加元数据metadataLabels
                Map<String, Object> labelsMap = new LinkedHashMap<>();
                labelsMap.put(DevOpsConstant.K8sConfig.K8S_LABELS, map);
                if ("Deployment".equals(kind)) {
                    value = setMetaDataLabels(value, map, labelsMap);

                    value = setMatchLabels(kubernetesResource.getProjectId(), value, name, map);
                } else {
                    value = setMetaDataLabels(value, map, labelsMap);
                }
            }


            DOSKubernetesResource resource = DOSKubernetesResource.builder()
                    .apiVersion(apiVersion)
                    .kind(kind)
                    .name(name)
                    .namespace(clusterNamespace.getNamespace())
                    .yamlValue(value)
                    .clusterId(kubernetesResource.getClusterId())
                    .namespaceId(kubernetesResource.getNamespaceId())
                    .envTypeId(kubernetesResource.getEnvTypeId())
                    .projectId(kubernetesResource.getProjectId())
                    .build();
            LambdaQueryWrapper<DOSKubernetesResource> queryWrapper = new LambdaQueryWrapper<>();
            if (kubernetesResource.getKubernetesResourceId() == null || kubernetesResource.getKubernetesResourceId() < 1){
                queryWrapper.eq(DOSKubernetesResource::getApiVersion,apiVersion)
                        .eq(DOSKubernetesResource::getKind,kind)
                        .eq(DOSKubernetesResource::getName,name)
                        .eq(DOSKubernetesResource::getNamespace,clusterNamespace.getNamespace())
                        .eq(DOSKubernetesResource::getClusterId,kubernetesResource.getClusterId())
                        .eq(DOSKubernetesResource::getProjectId,kubernetesResource.getProjectId())
                        .eq(DOSKubernetesResource::getEnvTypeId,kubernetesResource.getEnvTypeId());
                long count = this.count(queryWrapper);
                Assert.isTrue(count < 1,"名字为"+name+"的"+kind+"，已经存在，请勿重复部署，如需修改可升级");
            }

            // 判断yaml文件名称的相似度
            if (kubernetesResource.getCheckType() == 0 && type == 1) {
                // 创建时候判断相似度
                List<String> similarityName = baseMapper.getNameSimilarity(name, similarityLimit);
                Assert.isSimilar(ObjectUtil.isEmpty(similarityName), "已存在" + StringUtils.join(similarityName, ",") + "的" + kind + ",与" + name + "相似度太高，是否保存");
            }

            kubernetesResources.add(resource);
        }

        return kubernetesResources;
    }


    public Object getCertManagerInfo(String clusterName,String namespace) {
        Assert.isTrueMvc(StrUtil.isNotBlank(clusterName),"clusterName不能为空");
        if (StrUtil.isBlank(namespace)) {
            namespace = "default";
        }
        DOSClusterInfo clusterInfo = dosClusterInfoService.getClusterInfoByName(clusterName);
        Assert.isTrueMvc(clusterInfo != null && clusterInfo.getClusterId() != null,"clusterName不合法");

        CertManagerClient certManagerClient = CertManagerClientUtil.getCertManagerClient(clusterInfo.getConfigContent());

        CertificateList certificateList = certManagerClient.v1().certificates().inNamespace(namespace).list();
        ArrayList<HashMap<String,Object>> certificates = new ArrayList<>();
        for (int i=0;i<certificateList.getItems().size();i++) {
            Certificate certificate = certificateList.getItems().get(i);
            String kind = certificate.getKind();
            String name = certificate.getMetadata().getName();
            List<CertificateCondition> conditions = certificate.getStatus().getConditions();
            String lastTransitionTime = null;
            String status = null;
            if (conditions != null && conditions.size() > 0) {
                CertificateCondition certificateCondition = conditions.get(0);
                lastTransitionTime = certificateCondition.getLastTransitionTime();
                status = certificateCondition.getStatus();
            }
            HashMap<String,Object> map = new HashMap<>();
            map.put("kind",kind);
            map.put("name",name);
            map.put("namespace",namespace);
            map.put("lastTransitionTime",lastTransitionTime);
            map.put("status",status);

            certificates.add(map);

        }

        CertificateRequestList certificateRequestList = certManagerClient.v1().certificateRequests().inNamespace(namespace).list();
        ArrayList<HashMap<String,Object>> certificateRequests = new ArrayList<>();
        for (int i=0;i<certificateRequestList.getItems().size();i++) {
            CertificateRequest certificateRequest = certificateRequestList.getItems().get(i);
            String kind = certificateRequest.getKind();
            String name = certificateRequest.getMetadata().getName();
            List<CertificateRequestCondition> conditions = certificateRequest.getStatus().getConditions();
            String lastTransitionTime = null;
            String status = null;
            if (conditions != null && conditions.size() > 0) {
                CertificateRequestCondition condition = certificateRequest.getStatus().getConditions().get(0);
                lastTransitionTime = condition.getLastTransitionTime();
                status = condition.getStatus();
            }
            HashMap<String,Object> map = new HashMap<>();
            map.put("kind",kind);
            map.put("name",name);
            map.put("namespace",namespace);
            map.put("lastTransitionTime",lastTransitionTime);
            map.put("status",status);

            certificateRequests.add(map);
        }
        //OrderList orderList = certManagerClient.v1().orders().list();
        //ChallengeList challengeList = certManagerClient.v1().challenges().inNamespace(namespace).list();

//        KubernetesClient k8sClient = K8sClientUtil.getKubernetesClient(null, clusterInfo.getConfigContent());
//        SecretList secretList = k8sClient.secrets().inNamespace(namespace).list();

        HashMap<String,Object> map = new HashMap<>();
        map.put("certificateList",certificates);
        map.put("certificateRequestList",certificateRequests);
        //map.put("orderList",orderList);
        //map.put("challengeList",challengeList);
//        map.put("secretList",secretList);

        return map;
    }

    public Boolean dealCertManagerInfo(String clusterName,String namespace,String certificateName) {
        Assert.isTrueMvc(StrUtil.isNotBlank(clusterName), "clusterName不能为空");
        if (StrUtil.isBlank(namespace)) {
            namespace = "default";
        }
        DOSClusterInfo clusterInfo = dosClusterInfoService.getClusterInfoByName(clusterName);
        Assert.isTrueMvc(clusterInfo != null && clusterInfo.getClusterId() != null, "clusterName不合法");

        CertManagerClient certManagerClient = CertManagerClientUtil.getCertManagerClient(clusterInfo.getConfigContent());
        return !certManagerClient.v1().certificates().inNamespace(namespace).withName(certificateName).delete().isEmpty();
    }
    /**
     * @Author heyabo
     * @Description //TODO
     * @Date 20:19 2023/1/12
     * @Param [projectId, value, name, map]
     * @return java.lang.String
     **/
    private static String setMatchLabels(Integer projectId, String value, String name, Map<String, Object> map) {
        String matchLabelsKey = DevOpsConstant.K8sConfig.K8S_SELECTOR_MATCH_LABELS;
        Object matchLabelsObj = YamlUtils.getValues(matchLabelsKey, value);
        Map<String,Object> labelsMap = new LinkedHashMap<>();
        if (matchLabelsObj != null) {
            Map<String,Object> matchLabelsMap = (Map<String,Object>)matchLabelsObj;
            if (!matchLabelsMap.containsKey(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME)){
                labelsMap.put(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME, name);
            }
            if (!matchLabelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_PROJECT_ID)){
                labelsMap.put(DevOpsConstant.K8sConfig.K8S_LABEL_PROJECT_ID, projectId);
            }
            if (!matchLabelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_APPLY_TYPE)){
                labelsMap.put(DevOpsConstant.K8sConfig.K8S_LABEL_APPLY_TYPE,"yaml");
            }
            if (!matchLabelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_DEPLOYED_TYPE)){
                labelsMap.put(DevOpsConstant.K8sConfig.K8S_LABEL_DEPLOYED_TYPE,"devops");
            }
        }

        if (CollectionUtil.isNotEmpty(labelsMap)){
            String key = DevOpsConstant.K8sConfig.K8S_SELECTOR_MATCH_LABELS + ","
                    + DevOpsConstant.K8sConfig.K8S_TEMPLATE_METADATA_LABELS;
            value = YamlUtils.getUpdateYaml(key, labelsMap, value);
        }
//        if (values1 != null) {
//            String key = DevOpsConstant.K8sConfig.K8S_SELECTOR_MATCH_LABELS + ","
//                    + DevOpsConstant.K8sConfig.K8S_TEMPLATE_METADATA_LABELS;
//            if (values1 instanceof Map){
//                Map<String,Object> map1 = (Map<String,Object>)values1;
//                if (!map1.containsKey(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME)){
//                    value = YamlUtils.getUpdateYaml(key, matchLabelsMap, value);
//                }
//            }
//        }
        return value;
    }

    /**
     * @Author heyabo
     * @Description
     * @Date 20:15 2023/1/12
     * @Param [kubernetesResource, value, name]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    private static Map<String, Object> getLabelsValueToAddYaml(Integer projectId, String value, String name) {
        // 查询key为metadata的yaml值
        Object metadata = YamlUtils.getValues(DevOpsConstant.K8sConfig.K8S_METADATA, value);
        // 修改yaml文件
        Map<String,Object> map = new LinkedHashMap<>();
        if (metadata instanceof Map){
            Map<String,Object> metaDataMap = (Map<String,Object>)metadata;
            if (!metaDataMap.containsKey(DevOpsConstant.K8sConfig.K8S_METADATA)){
                map.put(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME, name);
                map.put(DevOpsConstant.K8sConfig.K8S_LABEL_PROJECT_ID, projectId);
                map.put(DevOpsConstant.K8sConfig.K8S_LABEL_APPLY_TYPE,"yaml");
                map.put(DevOpsConstant.K8sConfig.K8S_LABEL_DEPLOYED_TYPE,"devops");
            } else {
                Object labelsObj = metaDataMap.get(DevOpsConstant.K8sConfig.K8S_METADATA);
                if (labelsObj instanceof Map){
                    Map<String,Object> labelsMap = (Map<String,Object>)labelsObj;
                    if (!labelsMap.containsKey(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME)){
                        map.put(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME, name);
                    }
                    if (!labelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_PROJECT_ID)){
                        map.put(DevOpsConstant.K8sConfig.K8S_LABEL_PROJECT_ID, projectId);
                    }
                    if (!labelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_APPLY_TYPE)){
                        map.put(DevOpsConstant.K8sConfig.K8S_LABEL_APPLY_TYPE,"yaml");
                    }
                    if (!labelsMap.containsKey(DevOpsConstant.K8sConfig.K8S_LABEL_DEPLOYED_TYPE)){
                        map.put(DevOpsConstant.K8sConfig.K8S_LABEL_DEPLOYED_TYPE,"devops");
                    }
                }
            }
        }
        return map;
    }

    /**
     * @Author heyabo
     * @Description 为yaml文件设置metadataLabels标签
     * @Date 17:55 2023/1/12
     * @Param [value, map, labelsMap]
     * @return java.lang.String
     **/
    private static String setMetaDataLabels(String value, Map<String, Object> map, Map<String, Object> labelsMap) {
        String yaml = value;
        String key = DevOpsConstant.K8sConfig.K8S_METADATA + "." + DevOpsConstant.K8sConfig.K8S_LABELS;
        Object values = YamlUtils.getValues(key, value);
        if (values == null) {
            yaml = YamlUtils.addLabels(DevOpsConstant.K8sConfig.K8S_METADATA, labelsMap, value);
        } else {
            String yamlKey = DevOpsConstant.K8sConfig.K8S_METADATA + "."
                    + DevOpsConstant.K8sConfig.K8S_LABELS + "."
                    + DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME;
            Object values1 = YamlUtils.getValues(yamlKey, value);
            if (values1 == null){
                yaml = YamlUtils.getUpdateYaml(key, map, value);
            } else {
                if (values1 instanceof String) {
                    yaml = YamlUtils.getUpdateYaml(key, map, value);
                }
                if (values1 instanceof Map){
                    Map<String,Object> map1 = (Map<String,Object>)values1;
                    if (!map1.containsKey(DevOpsConstant.K8sConfig.POD_LABEL_RELEASE_NAME)){
                        yaml = YamlUtils.getUpdateYaml(key, map, value);
                    }
                }
            }
        }
        return yaml;
    }

}
